package com.forum.service.rank.service.impl;


import com.forum.service.rank.entity.vo.response.RankItemVO;
import com.forum.service.rank.service.UserActivityRankService;
import com.forum.service.user.entity.dto.Account;
import com.forum.service.user.service.AccountSchoolService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author lbwxxc
 * @date 2025/4/10 19:31
 * @description: 用户活跃相关
 */
@Service
public class UserActivityRankServiceImpl implements UserActivityRankService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    AccountSchoolService accountSchoolService;


    @Override
    //@Cacheable(cacheNames = "rankList")
    public List<RankItemVO> queryRankList() {
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        // 从 redis 中获取 zset
        Set<ZSetOperations.TypedTuple<String>> ranking = opsForZSet.rangeWithScores("ranking", 0, -1);
        List<RankItemVO> rankItemVOS = new ArrayList<>();
        if (ranking != null) {
            // 遍历键值对
            for (ZSetOperations.TypedTuple<String> tuple : ranking) {
                Account account = accountSchoolService.getAccountByAccountId(Integer.parseInt(Objects.requireNonNull(tuple.getValue())));
                RankItemVO rankItemVO = account.asViewObject(RankItemVO.class);
                rankItemVO.setScore(Objects.requireNonNull(tuple.getScore()).toString());
                rankItemVOS.add(rankItemVO);
            }
        }
        return rankItemVOS;
    }
}
